package ee.rsi2m.goproject.service;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import ee.rsi2m.goproject.MenuActivity;
import ee.rsi2m.goproject.R;
import ee.rsi2m.goproject.model.GoBoard;
import ee.rsi2m.goproject.model.GoGroup;
import ee.rsi2m.goproject.model.GoStone;
import ee.rsi2m.goproject.util.BoardLoader;
import ee.rsi2m.goproject.util.Constants;
import ee.rsi2m.goproject.util.DrawHelper;
import ee.rsi2m.goproject.util.GoGroupUtils;
import ee.rsi2m.goproject.util.Point;
import ee.rsi2m.goproject.util.StoneListHolder;
import ee.rsi2m.goproject.view.GoBoardView;

public class SurfaceViewThread extends Thread {

	private SurfaceHolder surfaceHolder;
	private boolean isRunning = false;

	private int turnCounter;
	ImageButton imageButton;
	private Context context;
	private GoBoard board;
	private Point minpoint = new Point(1, 1);
	private GoStone current = new GoStone();
	private boolean isBeingMoved;
	private boolean dialogValue;
	public Paint paint;
	private AlertDialog alert;
	private AlertDialog.Builder builder;
	
	private GoBoardView goBoardView;
	private Rect rectangle;
	private boolean isBackGroundDrawed;
	/** Used to figure out elapsed time between frames */
	private long mLastTime;
	/** Variables for the counter */
	private int frameSamplesCollected = 0;
	private int frameSampleTime = 0;
	private int fps = 0;
	boolean isNeeded = false;
	/** How to display the text */
	private Paint textPaint;
	private Bitmap anotherBackground;
	private Animation animation;
	private TextView tv;
	public Paint p;
	private Point HandicapPoints[];
	private StoneListHolder stoneListHolder;

	/*
	 * State-tracking constants
	 */
	public static final int STATE_LOSE = 1;
	public static final int STATE_PAUSE = 2;
	public static final int STATE_READY = 3;
	public static final int STATE_RUNNING = 4;
	public static final int STATE_WIN = 5;

	public SurfaceViewThread(SurfaceHolder surfaceHolder, GoBoard board, Context context, GoBoardView goBoardView, int handicap) {

		this.surfaceHolder = surfaceHolder;
		this.context = context;
		this.board = board;
		this.turnCounter = 0;
		stoneListHolder = new StoneListHolder();
		this.goBoardView = goBoardView;
		textPaint = new Paint();
		textPaint.setARGB(255, 255, 255, 255);
		textPaint.setTextSize(32);
		anotherBackground = BitmapFactory.decodeStream(context.getResources().openRawResource(R.drawable.gamescreenbackground));
		
		if (board.size == 19 || board.size == 13) {
			this.HandicapPoints = new Point[9];
			this.HandicapPoints[0] = new Point(4, 4);
			this.HandicapPoints[1] = new Point(4, board.size - 3);
			this.HandicapPoints[2] = new Point(board.size - 3, 4);
			this.HandicapPoints[3] = new Point(board.size - 3, board.size - 3);
			this.HandicapPoints[4] = new Point(4, (board.size - 1) / 2 + 1);
			this.HandicapPoints[5] = new Point((board.size - 1) / 2 + 1, (board.size - 1) / 2 + 1);
			this.HandicapPoints[6] = new Point(board.size - 3, (board.size - 1) / 2 + 1);
			this.HandicapPoints[7] = new Point((board.size - 1) / 2 + 1, 4);
			this.HandicapPoints[8] = new Point((board.size - 1) / 2 + 1, board.size - 3);
		}
		else
		{
			this.HandicapPoints = new Point[4];
			this.HandicapPoints[0] = new Point(3, 7);
			this.HandicapPoints[0] = new Point(7, 3);
			this.HandicapPoints[0] = new Point(7, 7);
			this.HandicapPoints[0] = new Point(3, 3);
		}

		board.assignBitmapToStone(context.getResources());
		board.initializeStoneAccordingToCounter(current);
		board.initializeBackground(context.getResources());
		Log.w("handicap", ":" + handicap);
		animation = AnimationUtils.loadAnimation(this.context, R.anim.animation);
		tv = (TextView) ((Activity) this.context).findViewById(R.id.thirdTextView);
		Log.w("text", "" + (tv == null));

		putStones(handicap);
	}

	private GoStone createStone(Point point, boolean visibility) {
		GoStone gstone = new GoStone(point, visibility, paint);
		if (board.getStoneColorByTurnCounter()) {
			gstone.initialize(Constants.WHITE, board.getWhiteStone(), turnCounter);
			turnCounter++;

		} else {
			gstone.initialize(Constants.BLACK, board.getBlackStone(), turnCounter);
			turnCounter++;


		}
		int[] pointDimensions = board.getPos(board.allpoints.indexOf(current.getPoint()));

		gstone.setRelativeX(pointDimensions[0]);
		gstone.setRelativeY(pointDimensions[1]);
		Log.w("Relative", "X:" + gstone.getRelativeX() + "Y:" + gstone.getRelativeY());

		board.boardState[pointDimensions[0]][pointDimensions[1]] = gstone;
		MenuActivity.playGTP("play " + "black " + getGTPValidMove(board.size, gstone.getRelativeX(), gstone.getRelativeY()));

		return gstone;
	}

	private void updatePhysics() {
		long now = System.currentTimeMillis();

		if (mLastTime != 0) {

			// Time difference between now and last time we were here
			int time = (int) (now - mLastTime);
			frameSampleTime += time;
			frameSamplesCollected++;

			// After 10 frames
			if (frameSamplesCollected == 10) {

				// Update the fps variable
				fps = (int) (10000 / frameSampleTime);

				// Reset the sampletime + frames collected
				frameSampleTime = 0;
				frameSamplesCollected = 0;
			}
		}

		mLastTime = now;
	}

	public void putStone() {
		addStoneToArray(createStone(current.getPoint(), true));
	}

	public boolean isGameBegan() {
		return current.getPoint() != null;
	}

	public boolean makeMoveByBot() {
		//Log.w("showgame", ""+BoardLoader.getInputStringLength(MenuActivity.playGTP("showboard")));
		//Log.w("showgame", ""+MenuActivity.playGTP("showboard"));

		String o = MenuActivity.playGTP("genmove " + "white");
		Log.w("GTP", "response" + o);
		if (o.contains("PASS")) {
			Log.w("endgame", "Result " + MenuActivity.playGTP("final_score"));
			return false;
		} else {
			Point point = responseToPoint(this.board.size, o);
			GoStone stone = board.boardState[(int) point.getX()][(int) point.getY()];

			GoStone gstone = new GoStone(new Point(stone.getX(), stone.getY()), true, paint);
			if (board.getStoneColorByTurnCounter()) {
				gstone.initialize(Constants.WHITE, board.getWhiteStone(), turnCounter);
			} else {
				gstone.initialize(Constants.BLACK, board.getBlackStone(), turnCounter);
			}

			gstone.setRelativeX((int) point.getX());
			gstone.setRelativeY((int) point.getY());

			board.boardState[gstone.getRelativeX()][gstone.getRelativeY()] = gstone;

			addStoneToArray(gstone);
		}
		Log.w("showgame", "!!"+MenuActivity.playGTP("showboard"));
		return true;
	}

	private void putStones(int handicap) {
		switch (handicap) {
		case 0:
		case 1:
			return;
		default:
			for (int i = 0; i < handicap && i < this.HandicapPoints.length; i++)
				// method for put actual stones on the board 
				// putHandicap((int)HandicapPoints[i].getX(), (int)HandicapPoints[i].getY());
				;
		
			board.turnCount++;
			Log.w("check", "PSH || ");
			//makeMoveByBot();
		}
	}

	private void putHandicap(int x, int y) {
		Log.w("check", "x " + x + " y " + y);
		GoStone stone = board.boardState[x][y];
		GoStone gstone = new GoStone(new Point(stone.getX(), stone.getY()), true, paint);

		gstone.initialize(Constants.BLACK, board.getBlackStone(), 1);
		gstone.setRelativeX(x);
		gstone.setRelativeY(y);
		board.boardState[x][y] = gstone;
		Log.w("check", gstone.toString() + " ");

		stoneListHolder.addStone(gstone);

		GoGroup group = new GoGroup();
		group.addStone(gstone);
		gstone.setGroup(group);
		gstone.getGroup().addLifePoints(4);
		MenuActivity.playGTP("play " + "black " + getGTPValidMove(board.size, x, y));
	}

	public void undo() {
		if (turnCounter > 0) {
			stoneListHolder.undo();
			this.turnCounter--;
		}
	}

	public boolean doTouch(MotionEvent event, ImageButton imageButton) {
		if (this.imageButton == null) {
			this.imageButton = imageButton;
		}

		board.initializeStoneAccordingToCounter(current);

		float x = event.getX();
		float y = event.getY();

		Point touchPoint = new Point(x, y);
		float minLength = 100000;

		for (int k = 0; k < board.size * board.size; k++) {
			if ((board.getLenght(board.allpoints.get(k), touchPoint) < minLength) && notContains(board.allpoints.get(k)) && board.notKo(board.allpoints.get(k))) {
				minLength = board.getLenght(board.allpoints.get(k), touchPoint);
				minpoint = board.allpoints.get(k);
			}
		}
		// Log.w("Minpoint", ""+minpoint.toString());
		/*
		 * backgroundBoard.set(backgroundBoard.left + 10, backgroundBoard.top +
		 * 10, backgroundBoard.right + 10, backgroundBoard.bottom + 10);
		 */
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			if (board.getBackgroundRect().contains((int) x, (int) y)) {
				isBeingMoved = false;
				current.setVisibility(true);
				break;
			}

		case MotionEvent.ACTION_MOVE:
			if (board.getBackgroundRect().contains((int) x, (int) y)) {
				isBeingMoved = true;

				current.setX(minpoint.getX());
				current.setY(minpoint.getY());
				current.setPoint(minpoint);
				break;
			}
			break;

		case MotionEvent.ACTION_UP:
			if (board.getBackgroundRect().contains((int) x, (int) y) && isBeingMoved) {
				isNeeded = true;
				break;
			}
		}
		// this.imageButton.setPressed(true);
		if (isNeeded) {
			this.imageButton.setSelected(true);
			this.imageButton.setEnabled(true);
		}

		isNeeded = false;
		return isNeeded;

	}

	public boolean notContains(Point point) {
		for (GoStone stone : stoneListHolder.getStones()) {
			if (point.getX() == stone.getX() && point.getY() == stone.getY() && stone.isVisibilible() && !stone.isKo()) {
				Log.w("notContains", "The stone's X relative is:" + stone.getRelativeX() + ";Stone's Y relative is:" + stone.getRelativeY());
				return false;
			}
		}
		return true;
	}

	private String getGTPValidMove(final int boardSize, int relativeX, int relativeY) {
		return Constants.ALPHABETICALCOORDINATES.charAt(boardSize - relativeX) + "" + relativeY;
	}
	
	public double getIntermediateResult()
    {
            if(turnCounter < 2)
                    return 0;
                    String tmp = MenuActivity.playGTP("estimate_score");
                    
                    String tmp2 = "";
                    if(tmp.charAt(2) == 'W')
                            tmp2 += "-";

                    for(int i = 4; tmp.charAt(i-2) != '.'; i++)
                    {
                            tmp2 += tmp.charAt(i);
                    }
                    
                    double aDouble = Double.parseDouble(tmp2);
                    Log.w("check", "Result " + tmp);
                    Log.w("check", "----------------");
                    Log.w("check", "Result " + aDouble);
                    return aDouble;

            //
    }

	public void addStoneToArray(GoStone gstone) {
		isBeingMoved = false;

		resetKoSituations();
		stoneListHolder.addStone(gstone);
		board.turnCount++;
		// TODO Refactoring: from int array create 2 variable for relative X and
		// Y

		List<GoGroup> groupList = getFriendlyNeighbourStoneGroupList(gstone);

		List<GoGroup> enemyneighbourStoneList = getNotFriendlyNeighbourStoneGroupList(gstone);
		Log.w("ENEMY1", enemyneighbourStoneList.size() + "");
		Log.w("Enemy", "Enemy Size is:" + enemyneighbourStoneList.size());
		Log.w("Group", "Friend list Size is:" + groupList.size());

		if (groupList.size() > 1) {

			for (GoGroup group : enemyneighbourStoneList) {
				group.decreaseLifePoints(1);
				// possible double deleting
				if (group.getLifePoints() < 1) {
					group.delete();
					for (GoGroup sgroup : board.getAllGroups(stoneListHolder)) {
						if (sgroup != null) {
							recalculateGroupLifepoints(sgroup);
						}
					}
				}
				Log.w("Enemy", "1Decreased lifepoints by:" + 1);
			}
			Log.w("FriendlyGroupList", groupList.size() + "");
			regroup(groupList, gstone);
		} else if (groupList.size() == 1) {
			groupList.get(0).addStone(gstone);
			gstone.setGroup(groupList.remove(0));
			recalculateGroupLifepoints(gstone.getGroup());
			Log.w("Friend", gstone.getGroup().toString());
			for (GoGroup group : enemyneighbourStoneList) {
				group.decreaseLifePoints(1);
				if (group.getLifePoints() < 1) {
					group.delete();
					for (GoGroup sgroup : board.getAllGroups(stoneListHolder)) {
						if (sgroup != null) {
							recalculateGroupLifepoints(sgroup);
						}
					}
				}
				Log.w("Enemy", "2Decreased lifepoints by:" + 1);
			}

		} else if (groupList.size() == 0) {

			for (GoGroup sgroup : enemyneighbourStoneList) {
				sgroup.decreaseLifePoints(1);
				Log.w("DECR", sgroup.toString());
				if (sgroup.getLifePoints() < 1) {
					Log.w("DeleteGroup", sgroup.toString());
					for (GoGroup group : board.getAllGroups(stoneListHolder)) {
						if (group != null) {
							recalculateGroupLifepoints(group, gstone.isCOLOR());
						}
					}
				}
				Log.w("Enemy", "3Decreased lifepoints by:" + 1);
			}

			GoGroup group = new GoGroup();
			group.addStone(gstone);
			gstone.setGroup(group);
			gstone.getGroup().addLifePoints((getDamePoints(gstone).size()));
			Log.w("Friend", group.toString());
		}
		for (GoGroup group : board.getAllGroups(stoneListHolder)) {
			Log.w("EveryGroup", group.toString());
		}
		Log.w("EveryGroup", "---------------");

	}

	private GoGroup regroup(List<GoGroup> groupList, GoStone gstone) {

		GoGroup mainGroup = GoGroupUtils.getBiggestGroup(groupList);
		groupList.remove(mainGroup);
		List<GoStone> k = GoGroupUtils.getStoneListToRegroup(groupList);
		Log.w("Stone", "X:" + gstone.getRelativeX() + " Y:" + gstone.getRelativeY());
		k.add(gstone);
		actualRegroup(k, mainGroup);
		return mainGroup;
	}

	private float getNumber(final String response) {
		if (response.length() == 6) {
			return (float) Integer.parseInt(response.charAt(3) + "");
		} else {
			return (float) Integer.parseInt("" + response.charAt(3) + response.charAt(4));
		}
	}

	private Point responseToPoint(final int size, final String response) {
		Log.w("NUMBER", "" + getNumber(response));
		Point p = new Point(size - Constants.ALPHABETICALCOORDINATES.indexOf(response.charAt(2)), getNumber(response));
		Log.w("BTM", response + " " + p);
		return p;
	}

	private void test(Point point) {
		GoStone stone = board.boardState[(int) point.getX()][(int) point.getY()];
		GoStone gstone = new GoStone(new Point(stone.getX(), stone.getY()), true, paint);
		gstone.initialize(Constants.WHITE, board.getWhiteStone(), turnCounter);
		Log.w("GTP", "x:" + gstone.getRelativeX() + " y:" + gstone.getRelativeY());
		resetKoSituations();
		stoneListHolder.addStone(gstone);
		board.turnCount++;
		// TODO Refactoring: from int array create 2 variable for relative X and
		// Y
		int[] pointDimensions = board.getPos(board.allpoints.indexOf(point));

		gstone.setRelativeX(pointDimensions[0]);
		gstone.setRelativeY(pointDimensions[1]);

		board.boardState[pointDimensions[0]][pointDimensions[1]] = gstone;
		List<GoGroup> groupList = getFriendlyNeighbourStoneGroupList(gstone);
		List<GoGroup> enemyneighbourStoneList = getNotFriendlyNeighbourStoneGroupList(gstone);
		Log.w("Enemy", "Enemy Size is:" + enemyneighbourStoneList.size());
		Log.w("Group", "Friend list Size is:" + groupList.size());

		if (groupList.size() > 1) {

			for (GoGroup group : enemyneighbourStoneList) {
				group.decreaseLifePoints(1);
				if (group.getLifePoints() < 1) {
					group.delete();
					for (GoGroup sgroup : board.getAllGroups(stoneListHolder)) {
						if (group != null) {
							recalculateGroupLifepoints(sgroup);
						}
					}
				}
				Log.w("Enemy", "1Decreased lifepoints by:" + 1);
			}
			Log.w("Friend", regroup(groupList, gstone).toString());
		} else if (groupList.size() == 1) {
			groupList.get(0).addStone(gstone);
			gstone.setGroup(groupList.remove(0));
			recalculateGroupLifepoints(gstone.getGroup());
			Log.w("Friend", gstone.getGroup().toString());
			for (GoGroup group : enemyneighbourStoneList) {
				group.decreaseLifePoints(1);
				if (group.getLifePoints() < 1) {
					group.delete();
					for (GoGroup sgroup : board.getAllGroups(stoneListHolder)) {
						if (group != null) {
							recalculateGroupLifepoints(sgroup);
						}
					}
				}
				Log.w("Enemy", "2Decreased lifepoints by:" + 1);
			}

		} else if (groupList.size() == 0) {

			for (GoGroup sgroup : enemyneighbourStoneList) {
				sgroup.decreaseLifePoints(1);
				if (sgroup.getLifePoints() < 1) {
					sgroup.delete();
					for (GoGroup group : board.getAllGroups(stoneListHolder)) {
						if (group != null) {
							recalculateGroupLifepoints(group, gstone.isCOLOR());
						}
					}
				}
				Log.w("Enemy", "3Decreased lifepoints by:" + 1);
			}
			Log.w("CoLOr", gstone.isCOLOR() + "");

			GoGroup group = new GoGroup();
			group.addStone(gstone);
			gstone.setGroup(group);
			gstone.getGroup().addLifePoints((getDamePoints(gstone).size()));
			Log.w("Friend", group.toString());
		}
	}

	private void resetKoSituations() {

		for (GoStone stone : stoneListHolder.getStones()) {
			if (stone.isKo()) {
				stone.setKo(false);
			}
		}
	}

	private void actualRegroup(List<GoStone> stoneListToRegroup, GoGroup mainGroup) {
		for (GoStone stone : stoneListToRegroup) {
			stone.setGroup(mainGroup);
		}
		mainGroup.addStones(stoneListToRegroup);
		Log.w("Groups", "" + mainGroup.getStones().size());
		mainGroup.printAllStoneCoord();

		recalculateGroupLifepoints(mainGroup);
		if (mainGroup.getLifePoints() < 1) {
			mainGroup.delete();
			for (GoGroup group : board.getAllGroups(stoneListHolder)) {
				if (group != null) {
					recalculateGroupLifepoints(group);
				}
			}
		}
	}

	private void recalculateGroupLifepoints(GoGroup mainGroup) {
		mainGroup.flushLifePoints();
		List<GoStone> damePoints = new ArrayList<GoStone>();

		for (GoStone stone : mainGroup.getStones()) {
			for (GoStone possibleDameStone : getDamePoints(stone)) {
				if (!damePoints.contains(possibleDameStone)) {
					damePoints.add(possibleDameStone);
				}
			}
		}

		Log.w("Groups", "Dame points:" + damePoints.size());
		mainGroup.setLifePoints(damePoints.size());
		Log.w("Groups", "Maingroup:" + mainGroup.toString());
	}

	private void recalculateGroupLifepoints(GoGroup mainGroup, boolean color) {
		if (mainGroup.getStones().get(0).isCOLOR() == color) {

			mainGroup.flushLifePoints();
			List<GoStone> damePoints = new ArrayList<GoStone>();
			for (GoStone stone : mainGroup.getStones()) {
				for (GoStone possibleDameStone : getDamePoints(stone)) {
					if (!damePoints.contains(possibleDameStone)) {
						damePoints.add(possibleDameStone);
					}
				}

			}
			Log.w("Groups", "Dame points:" + damePoints.size());
			mainGroup.setLifePoints(damePoints.size());
			Log.w("Groups", "Maingroup:" + mainGroup.toString());
		}
	}

	public List<GoStone> getDamePoints(GoStone stone) {
		Log.w("dame", "dameiscalled");
		List<GoStone> damePoints = new ArrayList<GoStone>();
		for (GoStone neighbourStone : GoGroupUtils.getFourNeighboursStoneList(stone, board)) {
			if (neighbourStone != null && !neighbourStone.isVisibilible()) {

				damePoints.add(neighbourStone);
			}
		}
		Log.w("dame", "dameiscalled");

		return damePoints;
	}

	public int getInterceptionCount(GoStone stone, GoGroup group) {
		int i = 0;
		for (GoStone neighbourStone : getFriendlyNeighbourStoneList(stone)) {
			if (neighbourStone.getGroup().equals(group)) {
				i++;
			}
		}
		return i;
	}

	private List<GoStone> getFriendlyNeighbourStoneList(GoStone stone) {
		List<GoStone> stoneList = new ArrayList<GoStone>();

		for (GoStone neighbourStone : GoGroupUtils.getFourNeighboursStoneList(stone, board)) {
			if (neighbourStone.isLogicNeigbour(stone) && neighbourStone.isVisibilible()) {
				stoneList.add(neighbourStone);
			}
		}

		return stoneList;
	}

	private List<GoStone> getNotFriendlyNeighbourStoneList(GoStone stone) {
		List<GoStone> stoneList = new ArrayList<GoStone>();
		for (GoStone neighbourStone : GoGroupUtils.getFourNeighboursStoneList(stone, board)) {
			if (neighbourStone != null && !neighbourStone.isLogicNeigbour(stone) && neighbourStone.isVisibilible()) {
				stoneList.add(neighbourStone);
			}
		}

		return stoneList;
	}

	private List<GoGroup> getNotFriendlyNeighbourStoneGroupList(GoStone stone) {
		List<GoGroup> goGroupList = new ArrayList<GoGroup>();

		for (GoStone neighbourStone : GoGroupUtils.getFourNeighboursStoneList(stone, board)) {
			if (neighbourStone != null && neighbourStone.getGroup() != null && !neighbourStone.isLogicNeigbour(stone) && neighbourStone.isVisibilible()
					&& !goGroupList.contains(neighbourStone.getGroup())) {
				goGroupList.add(neighbourStone.getGroup());
			}

		}

		return goGroupList;

	}

	private List<GoGroup> getFriendlyNeighbourStoneGroupList(GoStone stone) {

		List<GoGroup> goGroupList = new ArrayList<GoGroup>();

		for (GoStone neighbourStone : GoGroupUtils.getFourNeighboursStoneList(stone, board)) {
			if (neighbourStone != null && neighbourStone.getGroup() != null && neighbourStone.isLogicNeigbour(stone) && neighbourStone.isVisibilible()) {
				goGroupList.add(neighbourStone.getGroup());
			}

		}

		return goGroupList;

	}

	private void drawFPS(Canvas canvas) {

		// Draw the background color. Operations on the Canvas accumulate
		// so this is like clearing the screen. In a real game you can
		// put in a background image of cours

		// Draw fps center screen
		canvas.drawText(fps + " fps", 40, 100, textPaint);

		canvas.restore();
	}

	public void setRunning(boolean value) {
		this.isRunning = value;
	}

	public void displayLastStonePlaced(Canvas canvas,Paint paint) {
		/*if (stoneListHolder.getStones().size() > 0) {
			GoStone stone = stoneListHolder.getStones().get(stoneListHolder.getStones().size() - 1);
			Log.w("xy","X:"+stone.getX()+" Y:"+stone.getY());
			canvas.drawCircle(stone.getX(), stone.getY(),5,p);
		}else{
			p = new Paint();
			p.setColor(Color.CYAN);
		}*/
	}

	public void run() {
		Canvas canvas;
		Log.w("thread", "lol");
		if (imageButton != null) {
			this.imageButton.setPressed(true);
		}
		while (isRunning) {

			// tv.clearAnimation();
			// tv.startAnimation(animation);
			canvas = null;
			Log.w("thread", (canvas == null) + "");
			try {

				canvas = surfaceHolder.lockCanvas(null);
				/*
				 * if(!isBackGroundDrawed){
				 * canvas.drawBitmap(BitmapFactory.decodeStream
				 * (context.getResources()
				 * .openRawResource(R.drawable.gamescreenbackground)), 0,0,
				 * null); isBackGroundDrawed = true; }
				 */

				canvas.drawColor(0, PorterDuff.Mode.CLEAR);
				canvas.drawBitmap(anotherBackground, 0, 0, null);

				synchronized (surfaceHolder) {
					updatePhysics();
					// canvas.drawColor(Color.WHITE);
					board.draw(canvas);
					DrawHelper.drawEyes(canvas, board, paint);
					drawFPS(canvas);

					stoneListHolder.executeAll(canvas);
					if (isBeingMoved) {
						DrawHelper.drawVerticalGuideLine(canvas, current, paint);
						DrawHelper.drawHorizontalGuideLine(canvas, current, paint);
						current.draw(canvas);
					}
					displayLastStonePlaced(canvas,paint);

				}
			} finally {
				if (canvas != null) {
					surfaceHolder.unlockCanvasAndPost(canvas);
				}
			}
		}
	}

	public void pass() {
		String k = MenuActivity.playGTP("play " + "black " + "PASS");
		Log.w("response", k);

	}

	public String getScore() {
		return MenuActivity.playGTP("final_score");
		// TODO Auto-generated method stub

	}
}